/*
package com.jymj.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.*;
import com.jymj.common.annotation.SysLog;
import com.jymj.entity.KeyValueEntity;
import com.jymj.entity.PjProjEntity;
import com.jymj.entity.gantt.GanttLinkEntity;
import com.jymj.entity.gantt.PjTaskDetEntity;
import com.jymj.entity.gantt.PjTaskEntity;
import com.jymj.entity.gantt.PjtaskFile;
import com.jymj.service.PjProjService;
import com.jymj.service.PjTaskDelService;
import com.jymj.service.PjTaskFileService;
import com.jymj.service.PjTaskService;
import com.jymj.utils.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jymj.utils.DateUtils.BetweenDays;
import static org.aspectj.weaver.tools.cache.SimpleCacheFactory.path;

*/
/**
 * Created by dl on 2017/7/26.
 *//*

@RestController
@RequestMapping("/task")
@Transactional(rollbackFor = Exception.class)
public class PjTaskController extends AbstractController {

    private static final String SAVE_DIR = "progress";
    @Autowired
    private PjTaskService pjTaskService;
    @Autowired
    private PjTaskDelService pjTaskDelService;
    @Autowired
    private PjTaskFileService pjTaskFileService;
    //@Autowired
    //private SysLogService sysLogService;
    //@Autowired
    //CommonsMultipartResolver multipartResolver;
    //@Autowired
    //private RtInvestService rtInvestService;
    @Autowired
    private PjProjService pjProjService;

    ParseUtils parseUtils = new ParseUtils();
    List<PjTaskEntity> resultlist = new ArrayList();

    */
/**
     * gantt数据
     *
     *  pid
     * @param request
     * @param response
     *//*

    @RequestMapping("/init/{code}")
    public void init(@PathVariable("code") String code, HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> map = new HashMap<>();
            List<PjTaskEntity> tasks = pjTaskService.queryListByProj(code);
            List<GanttLinkEntity> linkList = pjTaskService.getLinkList(code);
            //排序
            //resultlist = new ArrayList<PjTaskEntity>();
            //sortList(tasks, 0);
            //checkTaskOrProject(tasks);
            getWaring(tasks);
            map.put("data", tasks);
            map.put("links", linkList);
            String dateFormat = "dd-MM-yyyy";
            SerializeConfig mapping = new SerializeConfig();
            mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));

            NameFilter nameFilter = (Object o, String s, Object o1) -> {
                if ("id".equals(s) && o.getClass() == PjTaskEntity.class) {
                    return "_id";
                } else if ("title".equals(s)) {
                    return "text";
                } else if ("taskid".equals(s)) {
                    return "id";
                } else if ("fatherid".equals(s)) {
                    return "parent";
                } else if ("t_start".equals(s)) {
                    return "start_date";
                } else if ("t_end".equals(s)) {
                    return "end_date";
                } else if ("days_planned".equals(s)) {
                    return "duration";
                } else if ("popmsg".equals(s)) {
                    return "popmsg";
                }
                return s;
            };
            PropertyFilter propertyFilter = (Object object, String name, Object value)
                    -> !(name.equals("days_planned") && value == null);
            ValueFilter valueFilter = (Object o, String propertyName, Object propertyValue) -> {
                if (propertyName.equals("type") && o.getClass() == PjTaskEntity.class) {
                    switch (parseUtils.ToInt(propertyValue)) {
                        case 0:
                            return "project";
                        case 1:
                            return null;
                        case 2:
                            return "milestone";
                    }
                    //返回修改后的属性值对象
                }
                return propertyValue;
            };
            SimplePropertyPreFilter filter = new SimplePropertyPreFilter(PjTaskEntity.class, "id", "taskid", "progress", "res", "t_start", "t_end", "title", "type", "waring", "fatherid", "days_planned", "cost", "status", "popmsg");
            SerializeFilter[] filters = {nameFilter, propertyFilter, filter, valueFilter};
            String json = JSON.toJSONString(map, mapping, filters);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(json);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    @RequestMapping("/childs/{code}")
    public String getChildTask(@PathVariable("code") String code) {
        String json;
        try {
            List<PjTaskEntity> tasks = pjTaskService.queryChildbyPid(code);
            SimplePropertyPreFilter filter = new SimplePropertyPreFilter(PjTaskEntity.class, "id", "title", "type");
            SerializeFilter[] filters = {filter};
            json = JSON.toJSONString(tasks, filters);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return "请求失败";
        }
        return json;
    }

    private void checkTaskOrProject(List<PjTaskEntity> tasks) {
        */
/**
         * project 0 task 1
         *//*

        if (tasks.size() > 0 && tasks.get(0).getType() == null) {
            tasks.stream().map((t) -> {
                List<PjTaskEntity> l = pjTaskService.queryChildTasks(t.getCode(), t.getTaskid());
                if (l == null || l.isEmpty()) {
                    t.setType(1);
                } else {
                    t.setType(0);
                    t.setT_end(null);
                    t.setT_start(null);
                    t.setDays_planned(null);
                }
                return t;
            }).forEachOrdered((t) -> {
                pjTaskService.updateById(t);
            });
        }
    }

    */
/**
     * 同init，只有进度值位数调整 资料管理
     *
     *  pid
     * @param request
     *//*

    @RequestMapping("/init1/{code}")
    public Map appFatherTask(@PathVariable("code") String code, HttpServletRequest request) throws Exception {
        List<PjTaskEntity> pjTaskEntityList = pjTaskService.queryListByProj(code);//全部
        List<PjTaskEntity> pjTaskEntities = new ArrayList<>();
        if(pjTaskEntityList!=null && pjTaskEntityList.size()>0){
            List<PjtaskFile> pjtaskFileList = pjTaskFileService.appFatherTask(pjTaskEntityList.get(0).getTaskid(),pjTaskEntityList.get(0).getCode());
            if (pjtaskFileList.size() > 0) {
                for (PjTaskEntity pjtask : pjTaskEntityList) {
                    List<PjtaskFile> fileList= new ArrayList<>();
                    for (PjtaskFile file:pjtaskFileList) {
                        if(file.getTid().equals(pjtask.getId()) ){
                            fileList.add(file);
                        }
                    }
                    pjtask.setPjtaskFileList(fileList);
                }
            }
            pjTaskEntities = getTreeOrgs(pjTaskEntityList,pjTaskEntityList.get(0).getFatherid());
        }
        //checkTaskOrProject(pjTaskEntityList);

        return R.ok().put("data", pjTaskEntities);
    }

    @RequestMapping("/getTask")
    public void getTask(HttpServletRequest request, HttpServletResponse response) {
        try {
            int id = parseUtils.ToInt(request.getParameter("id"));
            String code = request.getParameter("code");
            PjTaskEntity task = pjTaskService.queryObject1(code, id);
            Map<String, Object> map = new HashedMap();
            map.put("projId", task.getPjid());
            map.put("target", task.getTaskid());
            task.setLinks(pjTaskService.queryLinks(map));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JSON.toJSONString(task));
        } catch (IOException e1) {
            logger.error(e1.getMessage(), e1);
        }
    }

    */
/**
     * 获取任务列表 用于编辑界面
     *
     * @param request
     * @param response
     *//*

    @RequestMapping("/getTasks")
    public void getTasks(HttpServletRequest request, HttpServletResponse response) {
        try {
            ParseUtils parser = new ParseUtils();
            Map<String, Object> map = new HashMap<>();
            String code = request.getParameter("code");
            if (code ==  null) {
                return;
            }
            List<PjTaskEntity> tasks = pjTaskService.queryListByProj(code);
            NameFilter nameFilter = (Object o, String s, Object o1) -> {
                if (null != s) {
                    switch (s) {
                        case "id":
                            return "_id";
                        case "title":
                            return "text";
                        case "taskid":
                            return "id";
                        case "fatherid":
                            return "parent";
                        case "t_start":
                            return "start_date";
                        case "t_end":
                            return "end_date";
                        case "days_planned":
                            return "duration";
                        case "popmsg":
                            return "popmsg";
                        default:
                            break;
                    }
                }
                return s;
            };
            map.put("data", tasks);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JSON.toJSONString(map, nameFilter));
        } catch (IOException e1) {
            logger.error(e1.getMessage(), e1);
        }
    }

    //排序
    public void sortList(List<PjTaskEntity> list, int id) {
        list.stream().filter((node) -> (node.getFatherid() == id)).map((node) -> {
            if (node.getProgress() != null) {
                double f1 = SetScaleUtil.multiply(node.getProgress(), 2);
                node.setProgress(f1);
            } else {
                node.setProgress(0d);
            }
            return node;
        }).map((node) -> {
            resultlist.add(node);
            return node;
        }).forEachOrdered((node) -> {
            sortList(list, node.getTaskid());
        });
    }

    //计算滞后（红） 正常（黄） 超前（绿）
    public void getWaring(List<PjTaskEntity> list) {
        if (null == list) {
            return;
        }
        Date today = new Date();
        Calendar cToday = Calendar.getInstance();
        cToday.setTime(today);
        list.forEach((node) -> {
            if (node.getT_start() == null || node.getT_end() == null) {
            } else if (node.getProgress() == 0 && node.getT_start().getTime() >= today.getTime()) {
                node.setWaring(0);
            } else if (node.getT_end().getTime() >= today.getTime()) {//判断结束日期小于今天日期
                int daysplan = BetweenDays(node.getT_end(), node.getT_start());
                BigDecimal a1 = new BigDecimal(node.getProgress()).multiply(new BigDecimal(daysplan));
                Calendar cStart = Calendar.getInstance();
                cStart.setTime(node.getT_start());
                cStart.add(Calendar.DATE, a1.intValue());
                int result = cStart.compareTo(cToday);
                //如果 <0 即 c1< c2  不正常 滞后
                if (result < 0) {
                    node.setWaring(1);
                } else if (result == 0) {
                    node.setWaring(0);
                } else {
                    node.setWaring(2);
                }
            } else {//两种情况 滞后 正常
                if (node.getProgress() < 1) {
                    node.setWaring(1);
                }
            }
        });
    }

    @RequestMapping("/app/{code}")
    public Map init1(@PathVariable("code") String code) throws Exception {
        Map<String, Object> map = new HashMap<>();
        List<PjTaskEntity> tasks = pjTaskService.queryListByProj(code);
        //List<GanttLinkEntity> linkList = pjTaskService.getLinkList(pid);
        resultlist = new ArrayList<>();
        //sortList(tasks,0);
        if (tasks.size() > 0) {
            tasks.stream().map((node) -> {
                //BigDecimal b = new BigDecimal(node.getProgress());
                if (node.getProgress() != null) {
                    double f1 = SetScaleUtil.multiply(node.getProgress(), 2);
                    node.setProgress(f1);
                } else {
                    node.setProgress(0d);
                }
                return node;
            }).map((node) -> {
                Date toDay = new Date();
                Calendar cToday = Calendar.getInstance();
                cToday.setTime(toDay);
                //判断结束日期小于今天日期
                if (node.getT_end().getTime() >= toDay.getTime()) {
                    if (node.getProgress() < 100) {
                        int daysplan = BetweenDays(node.getT_end(), node.getT_start());
                        BigDecimal a1 = new BigDecimal(node.getProgress()).multiply(new BigDecimal(daysplan));
                        Calendar cStart = Calendar.getInstance();
                        cStart.setTime(node.getT_start());
                        cStart.add(Calendar.DATE, a1.intValue());
                        int result = cStart.compareTo(cToday);
                        //如果 <0 即 c1< c2  不正常 滞后
                        if (result < 0) {
                            node.setWaring(1);
                        } else if (result == 0) {
                            node.setWaring(0);
                        } else {
                            node.setWaring(2);
                        }
                    }
                } else {
                    if (node.getProgress() < 100) {
                        node.setWaring(1);
                    }
                }
                return node;
            }).forEachOrdered((node) -> {
                resultlist.add(node);
            });
        }
        map.put("data", resultlist);
        //map.put("links", linkList);
        return map;
    }

    @SysLog("android修改任务管理")
    @RequestMapping("/appUpdateTask")
    public String appUpdateTask(Integer pid, Integer taskid, String start, Integer duration) {
        try {
            //获取全部，用于迭代修改后续工作
            Map tasks = pjTaskService.queryMapWithLinkByProj(pid);
            PjTaskEntity oTask = (PjTaskEntity) tasks.get(taskid);
            PjTaskEntity target = (PjTaskEntity) tasks.get(taskid);
            target.setT_start(parseUtils.ToDate(start));
            target.setT_end(DateUtils.AddDay(target.getT_start(), duration));
            target.resetTask();
            int diff = DateUtils.BetweenDays(target.getT_end(), oTask.getT_end());
            //List<GanttLinkEntity> linkEntityList = target.getLinks();

            //修改task
            //遍历计算diff再保存 pjTaskService.updateExProgress(task);
            //修改links  先删除  在批量insert
            //pjTaskService.updateLinks(task, linkEntityList);
            updateTaskFollow(target, tasks, diff);
            pjTaskService.UpdateFatherCost(target);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return "error";
        }
        return "success";

        */
/*try {
            PjTaskEntity task = new PjTaskEntity();
            task.setPjid(pid);
            task.setTaskid(taskid);
            task.setCost(cost);
            task.setT_start(parseUtils.ToDate(start));
            task.setT_end(parseUtils.ToDate(end));
            pjTaskService.update(task);
        } catch (Exception e) {
            return "error";
        }
        return "success";*//*

    }

    //addTask
    @SysLog("添加任务管理")
    @RequestMapping("/addTask")
    //@RequiresPermissions("sys:oss:all")
    public R addTask(@RequestBody PjTaskEntity task, HttpServletRequest request) {
        task.setTaskid(task.getId());
        task.resetTask();
        Map tasks = pjTaskService.queryMapWithLinkByProj(task.getPjid());
        //task.setDays_planned(task.getDays_planned());
        List<GanttLinkEntity> linkEntityList = task.getLinks();
        //临时当前任务开始时间
        Date temp = task.getT_start();
        for (GanttLinkEntity link : linkEntityList) {
            if (link.getSource() == null || link.getType() == null) {
                continue;
            }
            //前置任务
            PjTaskEntity preTask = (PjTaskEntity) tasks.get(link.getSource());
            int delay = link.getDelay();
            int type = link.getType();
            //比较得出 开始时间
            Date startDate = getTempDate(type, delay, preTask, task);
            if (task.getT_start().compareTo(startDate) >= 0) {
                temp = task.getT_start();
            } else {
                temp = startDate;
            }
        }
        //重新赋值
        task.setT_start(temp);
        task.setT_end(DateUtils.AddDay(temp, task.getDays_planned()));
        pjTaskService.save(task);
        //修改links  先删除  在批量insert
        pjTaskService.updateLinks(task, linkEntityList);
        return R.ok().put("code", 0).put("msg", "添加成功！");
    }

    //一种修改工期时，推算紧后工作
    //一种修改后置任务中延期，遍历调整所有涉及
    //检查紧前 调整紧后
    private void updateTaskFollow1(PjTaskEntity t1, Map tasks, Integer amount) {
        PjTaskEntity target = (PjTaskEntity) tasks.get(t1.getTaskid());
        Date temp = DateUtils.AddDay(target.getT_end(), amount);
        //紧前工作
        Map<String, Object> map = new HashedMap();
        map.put("projId", target.getPjid());
        map.put("target", target.getTaskid());
        List<GanttLinkEntity> preLinks = pjTaskService.queryLinks(map);
        //计算关系中延搁后的最大时间
        for (GanttLinkEntity l : preLinks) {
            PjTaskEntity preTask = (PjTaskEntity) tasks.get(l.getSource());
            Date delayDate = DateUtils.AddDay(preTask.getT_end(), l.getDelay() + amount);
            if (temp == null || delayDate.compareTo(temp) > 0) {
                temp = delayDate;
            }
        }
        Integer diff;
        if (temp == null) {
            diff = DateUtils.BetweenDays(t1.getT_end(), target.getT_end());
        } else {
            diff = DateUtils.BetweenDays(temp, target.getT_end());
        }
        target.setT_start(DateUtils.AddDay(target.getT_start(), amount));
        target.setT_end(DateUtils.AddDay(target.getT_end(), amount));
        pjTaskService.updateById(target);
        //修改后续
        map = new HashedMap();
        map.put("projId", t1.getPjid());
        map.put("source", t1.getTaskid());
        List<GanttLinkEntity> backLinks = pjTaskService.queryLinks(map);
        backLinks.stream().map((l) -> (PjTaskEntity) tasks.get(l.getTarget())).forEachOrdered((backTask) -> {
            updateTaskFollow1(backTask, tasks, amount);
        });
    }

    private List<GanttLinkEntity> queryPreLinks(PjTaskEntity t) {
        //紧前工作
        Map<String, Object> map = new HashedMap();
        map.put("projId", t.getPjid());
        map.put("target", t.getTaskid());
        return pjTaskService.queryLinks(map);
    }

    private List<GanttLinkEntity> queryBackLinks(PjTaskEntity t) {
        //紧前工作
        Map<String, Object> map = new HashedMap();
        map.put("projId", t.getPjid());
        map.put("source", t.getTaskid());
        return pjTaskService.queryLinks(map);
    }

    private void updateTaskFollow(PjTaskEntity task, Map tasks, Integer amount) {
        */
/* try {*//*

        //旧当前task
        //PjTaskEntity target = (PjTaskEntity) tasks.get(task.getTaskid());
        Date temp = new Date(0);//task.getT_start();
        //前置任务links
        List<GanttLinkEntity> preLinks = queryPreLinks(task);
        if (null == preLinks || 0 == preLinks.size()) {
            temp = task.getT_start();
        }
        for (GanttLinkEntity link : preLinks) {
            if (link.getSource() == null || link.getType() == null) {
                continue;
            }
            //前置任务
            PjTaskEntity preTask = (PjTaskEntity) tasks.get(link.getSource());
            int delay = link.getDelay();
            int type = link.getType();
            //比较得出 开始时间
            Date re = getTempDate(type, delay, preTask, task);
            if (re.compareTo(temp) > 0) {
                temp = re;
            }
        }
        //重新赋值
        //if (temp.compareTo(new Date(2014, 1, 1)) <= 0) return;
        task.setT_start(temp);
        task.setT_end(DateUtils.AddDay(temp, task.getDays_planned()));
        pjTaskService.updateById(task);
        tasks.put(task.getTaskid(), task);
        List<GanttLinkEntity> backLinks = queryBackLinks(task);
        if (backLinks != null && backLinks.size() > 0) {
            backLinks.stream().map((l) -> (PjTaskEntity) tasks.get(l.getTarget())).filter((backTask)
                    -> (backTask != null)).forEachOrdered((backTask) -> {
                updateTaskFollow(backTask, tasks, amount);
            });
        }
    }

    //updateTask
    @SysLog("修改任务管理")
    @RequestMapping("/updateTask")
    public R updateTask(@RequestBody PjTaskEntity task, HttpServletRequest request) {
        //获取全部，用于迭代修改后续工作
        Map tasks = pjTaskService.queryMapWithLinkByProj(task.getPjid());
        //2017-11-7 by DL
        PjTaskEntity target = (PjTaskEntity) tasks.get(task.getTaskid());
        task.setType(target.getType());
        task.resetTask();
        int diff = task.getDays_planned();//DateUtils.BetweenDays(task.getT_end(), target.getT_end());
        List<GanttLinkEntity> linkEntityList = task.getLinks();
        */
/* by DL 2017-11-30
            if (task.getCost() != 0 && target.getCost() != 0 && task.getCost() != target.getCost()) {
                RtInvestEntity invest = new RtInvestEntity();
                invest.setCost(task.getCost());
                invest.setRefid(task.getId());
                rtInvestService.updateByRefId(invest);
            }*//*

        //修改task
        //遍历计算diff再保存 pjTaskService.updateExProgress(task);
        //修改links  先删除  在批量insert
        pjTaskService.updateLinks(task, linkEntityList);
        updateTaskFollow(task, tasks, diff);
        pjTaskService.UpdateFatherCost(task);
        return R.ok().put("code", 0).put("msg", "修改成功！");
    }

    //比较 得到一个开始时间
    public Date getTempDate(int type, int delay, PjTaskEntity preTask, PjTaskEntity task) {
        Date temp = task.getT_start();
        Integer days = task.getDays_planned();
        if (preTask != null) {
            //前置任务开始 结束 时间
            Date preStartDate = preTask.getT_start();
            Date preEndDate = preTask.getT_end();
            //当前任务开始 结束 时间
            Date startDate = task.getT_start();
            Date endDate = task.getT_end();
            //开始时间不参与计算，由前置任务关系决定
            if (0 == task.getStatus()) {
                startDate = new Date(0);
                //task.setStatus(-1);
            }
            //根据type  0完成-开始   1开始—开始    2完成—完成   3开始—完成
            switch (type) {
                case 0: {
                    Date date = DateUtils.AddDay(preEndDate, delay);
                    if (date.compareTo(startDate) >= 0) {
                        temp = date;
                    } else {
                        temp = startDate;
                    }
                    break;
                }
                case 1: {
                    Date date = DateUtils.AddDay(preStartDate, delay);
                    if (date.compareTo(startDate) >= 0) {
                        temp = date;
                    } else {
                        temp = startDate;
                    }
                    break;
                }
                case 2: {
                    Date date = DateUtils.AddDay(preEndDate, delay);
                    if (date.compareTo(endDate) >= 0) {
                        Date date1 = DateUtils.AddDay(date, -days);
                        temp = date1;
                    } else {
                        Date date1 = DateUtils.AddDay(endDate, -days);
                        temp = date1;
                    }
                    break;
                }
                default: {
                    Date date = DateUtils.AddDay(preStartDate, delay);
                    if (date.compareTo(endDate) >= 0) {
                        Date date1 = DateUtils.AddDay(date, -days);
                        temp = date1;
                    } else {
                        Date date1 = DateUtils.AddDay(endDate, -days);
                        temp = date1;
                    }
                    break;
                }
            }
        }
        return temp;
    }

    */
/**
     * delTask id为主键（_id）
     *
     * @param id
     * @param request
     * @return
     *//*

    @SysLog("删除任务管理")
    @RequestMapping("/delTask")
    public R delTask(Integer id, HttpServletRequest request) {
        if (id != null) {
            //判断是否有子集
            List<PjTaskEntity> taskEntities = pjTaskService.queryChildList(id);
            if (taskEntities != null && taskEntities.size() > 0) {
                return R.error("该项有子集，不能删除！");
            }
            //删除图片 记录 本身
            List<PjtaskFile> files = pjTaskFileService.queryFileByTid(id);
            files.removeAll(Collections.singleton(null));
            if (files.size() > 0) {
                String appPath = request.getServletContext().getRealPath("");
                // 构造文件存放的路径
                String savePath = appPath + File.separator + SAVE_DIR;
                files.stream().map((taskFile) -> new File(savePath + "\\" + taskFile.getFilepath()))
                        .forEachOrdered((file) -> {
                            file.delete();
                        });
            }
            pjTaskService.delete(id);
            //pjTaskFileService.deleteByTid(id);
        }

        return R.ok();
    }

    //addLink
    //@SysLog("添加任务管理关系链接")
    @RequestMapping("/addLink")
    //@RequiresPermissions("sys:oss:all")
    public R addLink(HttpServletRequest request) {
        try {
            ParseUtils parser = new ParseUtils();
            String param1 = StringEscapeUtils.unescapeHtml(request.getParameter("obj"));
            JSONObject obj = JSON.parseObject(param1);
            int pid = parser.ToInt(obj.get("pid"));
            String code = obj.get("code").toString();
            int type = parser.ToInt(obj.get("type"));
            int source = parser.ToInt(obj.get("source"));
            int target = parser.ToInt(obj.get("target"));
            int delay = parser.ToIntZero(obj.get("delay"));
            GanttLinkEntity ganttLink = new GanttLinkEntity();
            ganttLink.setPjid(pid);
            ganttLink.setSource(source);
            ganttLink.setTarget(target);
            ganttLink.setType(type);
            ganttLink.setDelay(delay);

            PjTaskEntity preT = pjTaskService.queryObject1(code, target);
            if (0 == preT.getType()) {
                return R.error("确定紧前工作为虚工作?");
            }

            pjTaskService.saveLink(ganttLink);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return R.error();
        }
        return R.ok();
    }

    //@SysLog("修改任务管理关系链接")
    @RequestMapping("/updateLink")
    public R updateLink(HttpServletRequest request) {
        try {
            ParseUtils parser = new ParseUtils();
            String param1 = StringEscapeUtils.unescapeHtml(request.getParameter("obj"));
            JSONObject obj = JSON.parseObject(param1);
            int pid = parser.ToInt(obj.get("pjid"));
            String code = obj.get("code").toString();
            int id = parser.ToInt(obj.get("_id"));
            int type = parser.ToInt(obj.get("type"));
            int source = parser.ToInt(obj.get("source"));
            int target = parser.ToInt(obj.get("target"));
            int delay = parser.ToIntZero(obj.get("delay"));
            GanttLinkEntity ganttLink = new GanttLinkEntity();
            ganttLink.setId(id);
            ganttLink.setPjid(pid);
            ganttLink.setSource(source);
            ganttLink.setTarget(target);
            ganttLink.setType(type);
            ganttLink.setDelay(delay);
            PjTaskEntity preT = pjTaskService.queryObject1(code, target);
            if (0 == preT.getType()) {
                return R.error("确定紧前工作为虚工作?");
            }
            pjTaskService.updateLink(ganttLink);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return R.error();
        }
        return R.ok();
    }

    //@SysLog("删除任务管理关系链接")
    @RequestMapping("/delLink")
    public R delLink(HttpServletRequest request) {
        try {
            ParseUtils parser = new ParseUtils();
            String param1 = StringEscapeUtils.unescapeHtml(request.getParameter("obj"));
            JSONObject obj = JSON.parseObject(param1);

            int pid = parser.ToInt(obj.get("pjid"));
            int id = parser.ToInt(obj.get("id"));
            GanttLinkEntity ganttLink = new GanttLinkEntity();
            ganttLink.setId(id);
            ganttLink.setPjid(pid);
            pjTaskService.delLink(ganttLink);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return R.error();
        }
        return R.ok();
    }

    */
/**
     * LJJ app 上传
     *
     * @param request
     * @return Map
     *//*

    //@SysLog("上传任务管理文件")
    @RequestMapping("/upload")
    public Map upload(HttpServletRequest request) throws FileNotFoundException {
        Map<String, Object> map = new HashMap();
        Integer id = null;
        //资料表实体
        PjtaskFile pjtaskFile = new PjtaskFile();
        // 获取根目录的绝对路径
        File genPath=new File(ResourceUtils.getURL("classpath:").getPath());
        if(!genPath.exists()){
            genPath=new File("");
        }
        //在开发测试模式时，得到地址为：{项目跟目录}/target/class/fileupload/progress/
        //在打成jar正式发布时，得到的地址为:{发布jar包目录}/fileupload/progress/
        File savePath=new File(genPath.getAbsolutePath(),"fileupload"+ File.separator+SAVE_DIR);
        if(!savePath.exists()){
            savePath.mkdirs();
            System.out.println("文件路径为：+"+savePath.getAbsolutePath());
        }
        //if (multipartResolver.isMultipart(request)) {
        //转换成多部分request
        MultipartHttpServletRequest multiRequest =null;
        if (request instanceof MultipartHttpServletRequest) {
            multiRequest = (MultipartHttpServletRequest)(request);
        }else {
            return R.error("文件不能为空！");
        }
        //取得request中的所有文件名
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            //取得上传文件
            MultipartFile file = multiRequest.getFile(iter.next());
            if (file != null) {
                //取得当前上传文件的文件名称
                String myFileName = file.getOriginalFilename();
                //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                if (!"".equals(myFileName.trim())) {
                    //重命名上传后的文件名
                    String fileName = file.getOriginalFilename();
                    //System.out.println(savePath + "\\" + fileName);
                    pjtaskFile.setActualname(fileName);
                    String ext = fileName.substring(fileName.indexOf("."));
                    TimeString st = new TimeString();
                    pjtaskFile.setFilepath(st.getTimeString() + ext);
                    //taskDetEntity.setSize(file.getSize());
                    String taskid1 = multiRequest.getParameter("taskid");
                    if (taskid1 != null && !taskid1.equals("")) {
                        pjtaskFile.setTaskid(Integer.parseInt(taskid1));
                    }
                    String code = multiRequest.getParameter("code");
                    if (code != null && !code.equals("")) {
                        pjtaskFile.setCode(code);
                    }
                    //pjtaskFile.setTaskid(taskid);
                    String actualname = multiRequest.getParameter("actualname");
                    if (actualname != null && !actualname.equals("")) {
                        pjtaskFile.setActualname(actualname);
                    }
                    String lng = multiRequest.getParameter("lng");
                    if (lng != null && !lng.equals("")) {
                        pjtaskFile.setLng(Double.parseDouble(lng));
                    }
                    String lat = multiRequest.getParameter("lat");
                    if (lat != null && !lat.equals("")) {
                        pjtaskFile.setLat(Double.parseDouble(lat));
                    }
                    String takerTime = multiRequest.getParameter("takerTime");
                    if (takerTime != null && !takerTime.equals("")) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            pjtaskFile.setTakerTime(sdf.parse(takerTime));
                        } catch (ParseException e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                    pjTaskFileService.save(pjtaskFile);
                    id = pjtaskFile.getId();
                    //上传路径
                    String path = savePath + File.separator + pjtaskFile.getFilepath();
                    //String path1=path.replaceAll( "/", "\\\\");
                    File localFile = new File(path);
                    try {
                        file.transferTo(localFile);
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                        return R.error("上传失败").put("code", 500);
                    }
                }
            } else {
                return R.error("文件不能为空！");
            }
        }
        //}
        map.put("data", id);
        map.put("msg", "上传成功！");
        map.put("code", 0);
        return map;
    }

    */
/**
     * ljj APP save 图片
     *
     * @param mstid
     * @param ids
     * @param request
     * @return
     *//*

    @SysLog("添加任务管理记录")
    @RequestMapping("/saveDel")
    public Map saveDel(Integer mstid, Integer[] ids, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            PjTaskDetEntity pjTaskDetEntity = new PjTaskDetEntity();
            pjTaskDetEntity.setMstid(mstid);
            String content = request.getParameter("content");
            if (content != null && !content.equals("")) {
                pjTaskDetEntity.setContent(content);
            }
            String progress = request.getParameter("progress");
            Double pro = null;
            if (progress != null && !progress.equals("")) {
                pro = SetScaleUtil.divide(Double.parseDouble(progress), 2);
                pjTaskDetEntity.setProgress(pro);
            }
            String uploadDate = request.getParameter("uploadDate");
            if (uploadDate != null && !uploadDate.equals("")) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    pjTaskDetEntity.setUploadDate(sdf.parse(uploadDate));
                } catch (ParseException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            String delId = request.getParameter("delId");
            if (delId != null && !delId.equals("")) {
                pjTaskDetEntity.setId(Integer.parseInt(delId));
            }

            pjTaskDetEntity.setType(0);
            pjTaskDetEntity.setUserUploadDate(new Date());
            pjTaskDetEntity.setUploadpsn(Integer.parseInt(getUserId().toString()));
            if (pjTaskDetEntity.getId() != null) {
                pjTaskDelService.upDate(pjTaskDetEntity);
            } else {
                pjTaskDelService.save(pjTaskDetEntity);
            }
            if (pro != null) {
                PjTaskEntity pjTaskEntity = pjTaskService.queryObject(mstid);
                pjTaskEntity.setProgress(pro);
                pjTaskService.update(pjTaskEntity);
            }
            Integer id = pjTaskDetEntity.getId();
            pjTaskFileService.update(id, ids);
        } catch (NumberFormatException e) {
            logger.error(e.getMessage(), e);
            map.put("code", 500);
            map.put("msg", "保存失败！");
            return map;
        }
        map.put("code", 0);
        map.put("msg", "保存成功！");
        return map;
    }

    */
/**
     * dl web save 点地图保存图片 2017-09-16
     *
     * @param mstid
     * @param ids
     * @param request
     * @return Map
     *//*

    @SysLog("上传任务管理地图图片")
    @RequestMapping("/webSaveDelPic")
    public Map webSaveDelPic(Integer mstid, Integer[] ids, HttpServletRequest request) {
        ParseUtils parser = new ParseUtils();
        Map<String, Object> map = new HashMap<>();
        try {
            PjTaskDetEntity pjTaskDetEntity = new PjTaskDetEntity();
            pjTaskDetEntity.setMstid(mstid);
            String content = request.getParameter("content");
            if (content != null && !content.equals("")) {
                pjTaskDetEntity.setContent(content);
            }
            String progress = request.getParameter("progress");
            Double pro = null;
            if (progress != null && !progress.equals("")) {
                pro = SetScaleUtil.divide(Double.parseDouble(progress), 2);
                pjTaskDetEntity.setProgress(pro);
            }
            String uploadDate = request.getParameter("uploadDate");
            if (uploadDate != null && !uploadDate.equals("")) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    pjTaskDetEntity.setUploadDate(sdf.parse(uploadDate));
                } catch (ParseException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            String delId = request.getParameter("delId");
            if (delId != null && !delId.equals("")) {
                pjTaskDetEntity.setId(Integer.parseInt(delId));
            }
            //添加經緯度 by DL 2017-9-16
            Double lng = parser.ToDouble(request.getParameter("lng"));
            Double lat = parser.ToDouble(request.getParameter("lat"));
            if (lng != 0.0 && lat != 0.0) {
                pjTaskDetEntity.setLat(lat);
                pjTaskDetEntity.setLng(lng);
            }
            pjTaskDetEntity.setType(2);
            pjTaskDetEntity.setUserUploadDate(new Date());
            pjTaskDetEntity.setUploadpsn(getUserId());
            if (pjTaskDetEntity.getId() != null) {
                pjTaskDelService.upDate(pjTaskDetEntity);
            } else {
                pjTaskDelService.save(pjTaskDetEntity);
            }
            if (pro != null) {
                PjTaskEntity pjTaskEntity = pjTaskService.queryObject(mstid);
                pjTaskEntity.setProgress(pro);
                pjTaskService.update(pjTaskEntity);
            }
            Integer id = pjTaskDetEntity.getId();
            if (ids != null && ids.length != 0) {
                pjTaskFileService.update(id, ids);
            }
        } catch (NumberFormatException e) {
            logger.error(e.getMessage(), e);
            map.put("code", 500);
            map.put("msg", "保存失败！");
            return map;
        }
        map.put("code", 0);
        map.put("msg", "保存成功！");
        return map;
    }

    */
/**
     * ljj web save 文件
     *
     * @param mstid
     * @param request
     * @param ids
     * @return Map
     *//*

    @SysLog("添加任务管理记录")
    @RequestMapping("/websaveDel")
    public Map saveDelFile(Integer mstid, Integer[] ids, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        Integer id;
        PjTaskDetEntity pjTaskDetEntity = new PjTaskDetEntity();
        pjTaskDetEntity.setMstid(mstid);
        String content = request.getParameter("content");
        if (content != null && !content.equals("")) {
            pjTaskDetEntity.setContent(content);
        }
        String code = request.getParameter("code");
        if (code != null && !code.equals("")) {
            pjTaskDetEntity.setCode(code);
        }
        String progress = request.getParameter("progress");
        Double pro = null;
        if (progress != null && !progress.equals("")) {
            pro = SetScaleUtil.divide(Double.parseDouble(progress), 2);
            pjTaskDetEntity.setProgress(pro);
        }
        String uploadDate = request.getParameter("uploadDate");
        if (uploadDate != null && !uploadDate.equals("")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                pjTaskDetEntity.setUploadDate(sdf.parse(uploadDate));
            } catch (ParseException e) {
                logger.error(e.getMessage(), e);
            }
        }
        String delId = request.getParameter("delId");
        if (delId != null && !delId.equals("")) {
            pjTaskDetEntity.setId(Integer.parseInt(delId));
        }
        pjTaskDetEntity.setType(1);
        pjTaskDetEntity.setUserUploadDate(new Date());
        pjTaskDetEntity.setUploadpsn(getUserId());
        if (pjTaskDetEntity.getId() != null) {
            pjTaskDelService.upDate(pjTaskDetEntity);
        } else {
            pjTaskDelService.save(pjTaskDetEntity);
        }
        if (pro != null) {
            PjTaskEntity pjTaskEntity = pjTaskService.queryObject(mstid);
            pjTaskEntity.setProgress(pro);
            pjTaskService.update(pjTaskEntity);
        }
        id = pjTaskDetEntity.getId();
        if (ids != null && ids.length != 0) {
            pjTaskFileService.update(id, ids);
        }
        map.put("code", 0);
        map.put("msg", "保存成功！");
        return map;
    }

    */
/**
     * 获取图片列表，用于地图右侧边栏显示 by DL 2017-09-16
     *
     * @param mstid
     * @param request
     * @param response
     *//*

    @RequestMapping("/getMapPicList")
    public void getMapPicList(Integer mstid, HttpServletRequest request, HttpServletResponse response) {
        try {
            */
/* String ip = InetAddress.getLocalHost().getHostAddress();
            String path = request.getScheme() + "://" + ip + ":" + request.getServerPort() + request.getContextPath() + "/";
             *//*

            Map<String, Object> map1 = new HashMap<>();

            List<PjTaskDetEntity> taskDets = pjTaskDelService.queryList(mstid);
            taskDets.forEach((td) -> {
                List<PjtaskFile> files = pjTaskFileService.queryList(td.getId());
                files.forEach((f) -> {
                    f.setFilepath(SAVE_DIR + "/" + f.getFilepath());
                });
                td.setTeskFile(files);
            });
            map1.put("msg", "成功");
            map1.put("data", taskDets);

            String dateFormat = "yyyy-MM-dd";
            SerializeConfig mapping = new SerializeConfig();
            mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JSON.toJSONString(map1, mapping));
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    */
/**
     * App获取项目照片 by DL 2017-10-09
     *
     * @param code
     * @param request
     * @param response
     *//*

    @RequestMapping("/getPicsForApp/{code}")
    public void getPicsForApp(@PathVariable("code") String code, HttpServletRequest request, HttpServletResponse response) {
        try {
            */
/*String ip = InetAddress.getLocalHost().getHostAddress();
            String path = request.getScheme() + "://" + ip + ":" + request.getServerPort() + request.getContextPath() + "/";
             *//*

            Map<String, Object> map1 = new HashMap<>();

            List<PjTaskDetEntity> taskDets = pjTaskDelService.queryPicForApp(code);

            Iterator<PjTaskDetEntity> it = taskDets.iterator();
            while (it.hasNext()) {
                PjTaskDetEntity boo = it.next();
                List<PjtaskFile> files = pjTaskFileService.queryList(boo.getId());
                files.forEach((f) -> {
                    f.setFilepath(SAVE_DIR + "/" + f.getFilepath());
                });
                boo.setTeskFile(files);
            }

            map1.put("msg", "成功");
            map1.put("data", taskDets);

            String dateFormat = "yyyy-MM-dd";
            SerializeConfig mapping = new SerializeConfig();
            mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JSON.toJSONString(map1, mapping));
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    */
/**
     * 根据范围查看图片 by DL 2017-10-09
     *
     * @param request
     * @param response
     *//*

    @RequestMapping("/getPicsByRange")
    public void getPicsByRange(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> map1 = new HashMap<>();
            ParseUtils parser = new ParseUtils();
            */
/*String ip = InetAddress.getLocalHost().getHostAddress();
            String path = request.getScheme() + "://" + ip + ":" + request.getServerPort() + request.getContextPath() + "/";
             *//*

            double x = parser.ToDouble(request.getParameter("x"));
            double x1 = parser.ToDouble(request.getParameter("x1"));
            double y = parser.ToDouble(request.getParameter("y"));
            double y1 = parser.ToDouble(request.getParameter("y1"));
            String code = request.getParameter("code");
            List<PjTaskDetEntity> taskDets = pjTaskDelService.queryByRange(x, y, x1, y1, code);
            taskDets.forEach((td) -> {
                List<PjtaskFile> files = pjTaskFileService.queryList(td.getId());
                files.forEach((f) -> {
                    f.setFilepath(SAVE_DIR + "/" + f.getFilepath());
                });
                td.setTeskFile(files);
            });
            map1.put("msg", "成功");
            map1.put("data", taskDets);

            String dateFormat = "yyyy-MM-dd";
            SerializeConfig mapping = new SerializeConfig();
            mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JSON.toJSONString(map1, mapping));
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    */
/**
     * ljj
     *
     * @param id
     * @param request
     * @return
     *//*

    @RequestMapping("/getTaskDelList/{id}")    //查询记录列表    任务主键   返回type
    public Map getTaskDelList(@PathVariable("id") Integer id, HttpServletRequest request) {
        Map<String, Object> map = new HashMap();
        //by dl 2017-09-26 “只获取资料列表” List<PjTaskDetEntity> taskDelList = pjTaskDelService.queryList(id);
        List<PjTaskDetEntity> taskDelList = pjTaskDelService.queryListOnlyTypeOne(id);
        taskDelList.forEach((task) -> {
            //SysUserEntity user = sysUserService.queryObject(task.getUploadpsn());
            task.setProgress(SetScaleUtil.multiply(task.getProgress(), 2));
            //task.setUserName(user.getUsername());
        });
        map.put("taskDelList", taskDelList);
        return map;
    }

    */
/**
     * ljj
     *
     * @param id
     * @param request
     * @return
     *//*

    @RequestMapping("/getTaskFileList/{id}")     // id为记录列表的主键
    public Map getTaskFileList(@PathVariable("id") Integer id, HttpServletRequest request) {
        */
/* String ip = null;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }*//*

        //String path = request.getScheme() + "://" + ip + ":" + request.getServerPort() + request.getContextPath() + "/";

        Map<String, Object> map = new HashMap();
        List<PjtaskFile> taskFileList = pjTaskFileService.queryList(id);
        List<PjtaskFile> pjTaskFileList = new ArrayList<>();
        if (taskFileList.size() > 0) {
            taskFileList.stream().map((task) -> {
                task.setFilepath(SAVE_DIR + "/" + task.getFilepath());
                return task;
            }).forEachOrdered((task) -> {
                pjTaskFileList.add(task);
            });
        }
        map.put("taskFileList", pjTaskFileList);
        return map;
    }

    */
/**
     * ljj
     *
     * @param id
     * @param request
     * @return
     *//*

    @RequestMapping("/appTaskFileList/{id}")
    public Map appTaskFileList(@PathVariable("id") Integer id, HttpServletRequest request) {
        */
/*String ip = null;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String path = request.getScheme() + "://" + ip + ":" + request.getServerPort() + request.getContextPath() + "\\";
         *//*

        Map<String, Object> map = new HashMap();
        List<PjtaskFile> taskFileList = pjTaskFileService.appqueryList(id);
        List<PjtaskFile> pjTaskFileList = new ArrayList<>();
        if (taskFileList.size() > 0) {
            taskFileList.stream().map((task) -> {
                task.setFilepath(SAVE_DIR + "\\" + task.getFilepath());
                return task;
            }).map((task) -> {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    // public final String format(Date date)
                    String s = sdf.format(task.getTakerTime());
                    task.setTakerDate(s);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                return task;
            }).forEachOrdered((task) -> {
                pjTaskFileList.add(task);
            });
        }
        map.put("code", 0);
        map.put("msg", "查询成功！");
        map.put("data", pjTaskFileList);
        return map;
    }

    */
/**
     * ljj 判断文件存不存在
     *
     * @param id
     * @param request
     * @param response
     * @return R
     *//*

    @RequestMapping("/hasFile/{id}")
    public R hasFile(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response) {
        String appPath = request.getServletContext().getRealPath("");
        String savePath = appPath + File.separator + SAVE_DIR;
        //删除文件
        PjtaskFile taskDet = pjTaskFileService.queryObject(id);
        String fileName = savePath + "/" + taskDet.getFilepath();

        File file = new File(fileName);
        if (!file.exists()) {
            logger.error("dowload_文件不存在", id);
            return R.ok().put("code", 500).put("msg", "文件不存在");
        } else {
            return R.ok();
        }

    }

    */
/**
     * ljj
     *
     * @param id
     * @param request
     * @param response
     *//*

    @SysLog("下载任务管理文件")
    @RequestMapping("/dowload/{id}")
    public void dowload(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response) {
        try {
            String appPath = request.getServletContext().getRealPath("");
            String savePath = appPath + File.separator + SAVE_DIR;
            //删除文件
            PjtaskFile taskDet = pjTaskFileService.queryObject(id);
            String fileName = savePath + "/" + taskDet.getFilepath();

            File file = new File(fileName);
            if (file.exists()) {
                // 读到流中
                InputStream inStream = new FileInputStream(fileName);
                // 设置输出的格式
                response.reset();
                response.setContentType("bin");
                response.addHeader("Content-Disposition", "attachment; filename=\"" + taskDet.getActualname() + "\"");
                // 循环取出流中的数据
                */
/* byte[] b = new byte[10240];
                int len;
                while ((len = inStream.read(b)) > 0) {
                    response.getOutputStream().write(b, 0, len);
                }
                OutputStream os = response.getOutputStream();
                os.flush();
                os.close();*//*

                inStream.close();
                response.getWriter().print(JSON.toJSONString(R.ok()));
            } else {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().print(JSON.toJSONString(R.ok().put("code", 500).put("msg", "文件不存在")));
                logger.error("dowload_文件不存在", id);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    //构建树
    public List<PjTaskEntity> getTreeOrgs(List<PjTaskEntity> allOrgs,Integer fatherid) throws Exception {
        List<PjTaskEntity> listParentRecord = new ArrayList<PjTaskEntity>();
        List<PjTaskEntity> listNotParentRecord = new ArrayList<PjTaskEntity>();
        // 第一步：遍历allOrgs找出所有的根节点和非根节点
        if (allOrgs != null && allOrgs.size() > 0) {
            allOrgs.forEach((org) -> {
                if (fatherid == org.getFatherid()) {
                    listParentRecord.add(org);
                } else {
                    listNotParentRecord.add(org);
                }
            });
        }
        // 第二步： 递归获取所有子节点
        if (listParentRecord.size() > 0) {
            for (PjTaskEntity record : listParentRecord) {
                // 添加所有子级
                record.setChildren(this.getChildOrgs(listNotParentRecord, record.getTaskid()));
            }
        }
        return listParentRecord;
    }

    public List<PjTaskEntity> getChildOrgs(List<PjTaskEntity> childList, Integer fatherid) throws Exception {
        List<PjTaskEntity> listParentOrgs = new ArrayList<>();
        List<PjTaskEntity> listNotParentOrgs = new ArrayList<>();
        // 遍历childList，找出所有的根节点和非根节点
        if (childList != null && childList.size() > 0) {
            childList.forEach((record) -> {
                // 对比找出父节点
                if (record.getFatherid().equals(fatherid)) {
                    listParentOrgs.add(record);
                } else {
                    listNotParentOrgs.add(record);
                }
            });
        }
        // 查询子节点
        if (listParentOrgs.size() > 0) {
            for (PjTaskEntity record : listParentOrgs) {
                // 递归查询子节点
                record.setChildren(getChildOrgs(listNotParentOrgs, record.getTaskid()));
            }
        }
        return listParentOrgs;
    }

    */
/**
     * 组装末级数据，末级资料文件数据
     *
     * @param target
     * @param childs
     *//*

    private void GetChilds(PjTaskEntity target, List<PjTaskEntity> childs, String path) {
        if (target != null) {
            childs.forEach((t) -> {
                List<PjTaskEntity> reChilds = pjTaskService.queryChildTasks(t.getCode(), t.getTaskid());
                //迭代直到末级，将末级添加到子集合；添加任务所有资料文件
                if (reChilds != null && reChilds.size() > 0) {
                    GetChilds(target, reChilds, path);
                } else {
                    List<PjtaskFile> pjtaskFileList = pjTaskFileService.appFatherTask(t.getTaskid(), t.getCode());
                    if (pjtaskFileList.size() > 0) {
                        pjtaskFileList.forEach((file) -> {
                            file.setFilepath(SAVE_DIR + "/" + file.getFilepath());
                        });
                        t.setPjtaskFileList(pjtaskFileList);
                    }
                    target.getChildren().add(t);
                }
            });
        }
    }

    */
/**
     * 删除图片
     *
     * @param id
     * @param request
     * @param response
     * @return Map
     *//*

    @SysLog("删除任务管理图片")
    @RequestMapping("/delete/{id}")
    public Map delete(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap();
        try {
            File genPath=new File(ResourceUtils.getURL("jar:").getPath());
            File savePath=new File(genPath.getAbsolutePath().replace("jar:","fileupload"),File.separator+SAVE_DIR);
            PjtaskFile taskDet = pjTaskFileService.queryObject(id);
            String fileName = savePath + File.separator + taskDet.getFilepath();
            //删除文件
            File file = new File(fileName);
            file.delete();
            pjTaskFileService.delete(taskDet.getId());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("code", 500);
            map.put("msg", "删除失败！");
            return map;
        }
        map.put("code", 0);
        map.put("msg", "删除成功！");
        return map;
    }

    */
/**
     * 删除记录
     *
     * @param id
     * @param request
     * @param response
     * @return Map
     *//*

    @SysLog("删除任务管理记录")
    @RequestMapping("/deleteDel/{id}")
    public Map deleteDel(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap();
        try {
            String appPath = request.getServletContext().getRealPath("");
            String savePath = appPath + File.separator + SAVE_DIR;
            List<PjtaskFile> taskDetList = pjTaskFileService.queryList(id);
            if (taskDetList.size() > 0) {
                taskDetList.stream().map((taskfile) -> savePath + "/" + taskfile.getFilepath())
                        .map((fileName) -> new File(fileName)).forEachOrdered((file) -> {
                    //删除文件
                    file.delete();
                });
            }
            pjTaskFileService.deleteByDelId(id);
            pjTaskDelService.delete(id);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("code", 500);
            map.put("msg", "删除失败！");
            return map;
        }
        map.put("code", 0);
        map.put("msg", "删除成功！");
        return map;
    }

    */
/**
     * 获取资金表 by dl 2017-08-22
     *
     * @param pid
     * @param request
     * @param response
     *//*

    @RequestMapping("/contracts/{code}")
    public void contracts(@PathVariable("code") String code, HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> map = new HashMap<>();
            List<PjTaskEntity> contractList = pjTaskService.queryContractList(code);
            ArrayList<String> xdata = new ArrayList<>();
            ArrayList<Double> ydata = new ArrayList<>();
            contractList.stream().map((task) -> {
                ydata.add(task.getCost());
                return task;
            }).forEachOrdered((task) -> {
                xdata.add(task.getTitle());
            });
            map.put("xdata", xdata.toArray());
            map.put("ydata", ydata.toArray());
            //String re = JSON.toJSONString(map, propertyPreFilter);
            String re = JSON.toJSONString(map);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(re);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    */
/**
     * 投资计划表 by dl 2017-08-23
     *
     * @param pid
     * @param request
     * @param response
     *//*

    @RequestMapping("/tzjh/{code}")
    public void tzjh(@PathVariable("code") String code, HttpServletRequest request, HttpServletResponse response) {
        try {
            ParseUtils parser = new ParseUtils();
            ArrayList<String> xdata = new ArrayList<>();
            ArrayList<Object> ydata = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Map<String, Object> map = pjTaskService.queryDateRange(code);
            Map<String, Object> reMap = new LinkedHashMap();
            Date start = parser.ToDate(map.get("min"));
            Date end = parser.ToDate(map.get("max"));
            int monthStart = (int) (start.getYear() * 12 + start.getMonth() - 1);
            int monthEnd = (int) (end.getYear() * 12 + end.getMonth());
            StrBuilder str = new StrBuilder();
            str.append("select ");
            while (monthStart < monthEnd) {
                int y = monthStart / 12;
                int m = monthStart % 12 + 1;
                String strDate = sdf.format(new Date(y, m, 1));
                str.append(" SUM(CASE to_char(t_end,'yyyy-MM') WHEN '" + strDate + "' THEN cost else 0 end) \"" + strDate + "\",");
                monthStart++;
            }
            str.delete(str.length() - 1, str.length());
            str.append(" FROM pj_task where pjid=" + code + " and iscontract=1;");
            reMap.put("xdata", xdata);
            reMap.put("ydata", ydata);
            String re = JSON.toJSONString(reMap);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(re);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    */
/**
     * 成本测算 by ljj pjid 工程id i 1--年 2--季 3-月
     *
     * @param code
     * @param i
     * @return List
     *//*

    @RequestMapping("/cbcs")
    //public List<Map<String, Object>> cbcs(Integer pjid, Integer i) {
    public List<KeyValueEntity> cbcs(String code, Integer i) {
        List<KeyValueEntity> map = new ArrayList();
        if (i != null) {
            switch (i) {
                case 1:
                    map = pjTaskService.queryCzByYear(code);
                    break;
                case 2:
                    break;
                default:
                    map = pjTaskService.queryCzByMonth(code);
                    break;
            }
        }
        return map;
    }

    */
/**
     * 构建末级
     *
     * @param target
     * @param childs
     *//*

    private void GetChilds(PjTaskEntity target, List<PjTaskEntity> childs) {
        if (target != null) {
            for (PjTaskEntity t : childs) {
                List<PjTaskEntity> reChilds = pjTaskService.queryChildTasks(t.getCode(), t.getTaskid());
                //迭代直到末级，将末级添加到子集合；添加任务所有资料文件
                if (reChilds != null && reChilds.size() > 0)
                    GetChilds(target, reChilds);
                else {
                    List<PjtaskFile> pjtaskFileList = pjTaskFileService.appFatherTask(t.getTaskid(), t.getCode());
                    if (pjtaskFileList.size() > 0) {
                        */
/*for (PjtaskFile file : pjtaskFileList) {
                            file.setFilepath(path + SAVE_DIR + "/" + file.getFilepath());
                        }*//*

                        t.setPjtaskFileList(pjtaskFileList);
                    }
                    target.getChildren().add(t);
                }
            }
        }
    }

    */
/**
     * 构建编号并排序
     *
     * @param list
     * @param num
     *//*

    private void BuildOrderNum(List<PjTaskEntity> list, int id, String num) {
        list.stream().filter((node) -> (node.getFatherid() == id)).map((node) -> {
            if ("".equals(num)) {
                node.setDesc(parseUtils.ToString(node.getOrderid() + 1));
            } else {
                node.setDesc(num + "." + parseUtils.ToString(node.getOrderid() + 1));
            }
            return node;
        }).map((node) -> {
            resultlist.add(node);
            return node;
        }).forEachOrdered((node) -> {
            BuildOrderNum(list, node.getTaskid(), node.getDesc());
        });
    }

    */
/**
     * 构建编号并排序
     *
     * @param list
     * @param num
     *//*

    private void BuildOrderNum(List<PjTaskEntity> list, int num) {
        int i = 1;
        for (PjTaskEntity node : list) {
            node.setDesc(num + "." + i);
            i++;
            resultlist.add(node);
        }
    }

    */
/**
     * 获取前置任务 2017-09-13 by DL
     *
     * @param request
     * @param response
     *//*

    @RequestMapping("/GetPreTasks")
    public void GetPreTasks(HttpServletRequest request, HttpServletResponse response) {
        ParseUtils parser = new ParseUtils();
        Integer pid = parser.ToInt(request.getParameter("pid"));
        Integer taskid = parser.ToInt(request.getParameter("taskid"));
        Map<String, Object> map = new HashMap<>();
        map.put("pid", pid);
        map.put("target", taskid);
        List<GanttLinkEntity> data = pjTaskService.getPreTasks(map);
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JSON.toJSONString(R.ok().put("data", data)));
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }


    */
/*
 * 所有项目的进度
     *//*

    @RequestMapping("/getAllTask")
    public String getAllTask() {
        String json;
        Map map = new HashMap();
        try {
            List<PjProjEntity> proList = pjProjService.queryTotalPro();
            List<PjTaskEntity> taskList = pjTaskService.queryAllTask();
            map.put("proList", proList);
            map.put("taskList", taskList);
            SimplePropertyPreFilter filter = new SimplePropertyPreFilter(PjTaskEntity.class, "id", "taskid", "progress", "t_start", "t_end", "title", "type", "days_planned", "cost", "pjid");
            SimplePropertyPreFilter filter1 = new SimplePropertyPreFilter(PjProjEntity.class, "id", "name");
            SerializeFilter[] filters = {filter, filter1};
            json = JSON.toJSONString(map, filters);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("code", 500);
            map.put("msg", "请求数据失败！");
            json = JSON.toJSONString(map);
            return json;
        }
        return json;
    }

}
*/
